package com.yunduo.controller.front;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.JwtUtils;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.common.YunDuoConst.OrderState;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.*;
import com.yunduo.entity.front.OrderDetail;
import com.yunduo.entity.front.OrderDetailList;
import com.yunduo.entity.vo.OrderVo;
import com.yunduo.service.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * 前端订单信息查询
 */
@RestController
@RequestMapping("/forder")
public class OrderDetailController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private OrderService orderService;

    @Resource
    private PayService payService;

    @Resource
    private UserService userService;

    @Resource
    private AddressService addressService;

    @Resource
    private GoodService goodService;

    /**
     * 订单分类查询
     * @param type
     * @return
     */
    @GetMapping("/orderType")
    public CommonReturn orderType(String type){
        switch (type){
            case "0":
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
                break;
            default:
                return CommonReturn.ERROR(ResultCode.ERROR);
        }
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        LambdaQueryWrapper<Order> orderQuery = new LambdaQueryWrapper<>();
        if(!OrderState.ORDER_ALL.equals(type)){
            orderQuery.eq(Order::getState,type);
        }
        orderQuery.eq(Order::getUserId,user.getId());
        List<Order> orderData = orderService.list(orderQuery);
        List<OrderVo> orderVos = new ArrayList<>();
        Iterator<Order> iterator = orderData.iterator();
        //订单列表其他讯息组合
        while (iterator.hasNext()){
            Order item = iterator.next();
            OrderVo orderVo = new OrderVo();
            orderVo.setId(item.getId());
            orderVo.setState(OrderState.getStateCN(item.getState()));
            orderVo.setPrice(item.getPay().toString());
            ArrayList<String> orderIds = YunDuoUtils.OrderIdsSplit(item.getShop());
            //每个订单显示第一个商品的图片
            Good imgGood = goodService.getById(orderIds.get(0));
            orderVo.setUrl(imgGood.getCover());
            //拼接商品名
            Set<Good> goods = goodService.getOrdersByOrderInfo(item.getShop()).keySet();
            StringBuffer goodNames= new StringBuffer();
            String[] goodNameData = goods.stream().map(Good::getName).toArray(String[]::new);
            for (int i = 0; i < goodNameData.length; i++) {
                goodNames.append(goodNameData[i]+" ");
            }
            orderVo.setShopNames(goodNames.toString());
            orderVos.add(orderVo);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("data",orderVos);
    }

    /**
     * 查询订单详细信息
     * @param id
     * @return
     */
    @GetMapping("/orderInfo/{id}")
    public CommonReturn orderInfo(@PathVariable("id") String id){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        OrderDetailList data = new OrderDetailList();
        Order order = orderService.getById(id);
        Address address = addressService.getById(order.getAddress());
        data.setAddress(address.getAddress());
        data.setPhone(address.getPhone());
//        String phone = YunDuoUtils.phoneEncode(address.getPhone());
        User orderUser = userService.getById(user.getId());
        data.setUserName(orderUser.getName());
        //支付记录
        Pay isPay = payService.getOne(new LambdaQueryWrapper<Pay>().eq(Pay::getUserId, user.getId()).eq(Pay::getOrderId, id));
        if(isPay!=null) {
            data.setPay(isPay.getMoney());
            data.setPayIs(true);
            data.setPayCode(isPay.getId());
        }else{
            data.setPayIs(false);
        }
        //商品内容
        List<OrderDetail> orderDetails = new ArrayList<>();
        String[] goods = order.getShop().split(",");
        for (int i = 0; i < goods.length; i++) {
            String goodInfo = goods[i];
            String[] good = goodInfo.split("\\*");
            Good goodData = goodService.getById(good[0]);
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setCount(Integer.valueOf(good[1]));
            orderDetail.setName(goodData.getName());
            orderDetail.setPrice(goodData.getPrice());
            orderDetail.setImgUrl(goodData.getCover());
            orderDetails.add(orderDetail);
        }
        long creteTime = 0;
        if(order.getState().equals(OrderState.DELAY_PAY)){
            //获取订单创建时间
            ValueOperations redis = redisTemplate.opsForValue();
            creteTime = Long.valueOf((String) redis.get(id));
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("data",data).setData("orderDetails",orderDetails)
                .setData("createTime",creteTime);
    }

    /**
     * 用户取消订单
     * @param id
     * @return
     */
    @GetMapping("/giveupOrder/{id}")
    public CommonReturn giveUpOrder(@PathVariable("id")String id){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        String userId = user.getId();
        Order order = orderService.getById(id);
        if(!order.getState().equals(OrderState.DELAY_PAY)){
            return CommonReturn.ERROR(ResultCode.REQUEST_UNDEFINE);
        }
        if(!order.getUserId().equals(userId)){
            return CommonReturn.ERROR(ResultCode.REQUEST_UNDEFINE);
        }
        order.setState(OrderState.PAY_CANCEL);
        orderService.updateById(order);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }
}
